<template>
	<view class="page-body">
		<!-- 页面内容开始 -->

		<!-- 表格搜索组件开始 -->
		<vk-data-table-query v-model="queryForm1.formData" :columns="queryForm1.columns" @search="search">
		</vk-data-table-query>
		<!-- 表格搜索组件结束 -->

		<!-- 自定义按钮区域开始 -->
		<view>
			<el-row>
				<!-- <el-button type="success" size="small" icon="el-icon-circle-plus-outline" @click="addBtn">添加单集
				</el-button>
				<el-button type="success" size="small" icon="el-icon-circle-plus-outline" @click="batchaddBtn">批量添加剧集
				</el-button>
				<el-button type="success" size="small" @click="update_appid">重置全部appid</el-button> -->
				<!-- 批量操作 -->
				<el-dropdown v-if="table1.multipleSelection" :split-button="false" trigger="click" @command="batchBtn">
					<el-button type="danger" size="small" style="margin-left: 20rpx;"
						:disabled="table1.multipleSelection.length === 0">
						批量操作<i class="el-icon-arrow-down el-icon--right"></i>
					</el-button>
					<el-dropdown-menu slot="dropdown">
						<el-dropdown-item :command="1">批量删除</el-dropdown-item>
						<el-dropdown-item :command="2">批量改价</el-dropdown-item>
					</el-dropdown-menu>
				</el-dropdown>
			</el-row>
		</view>
		<!-- 自定义按钮区域结束 -->

		<!-- 表格组件开始 -->
		<vk-data-table ref="table1" :action="table1.action" :columns="table1.columns" :query-form-param="queryForm1"
			:right-btns="['detail_auto','update','delete']" :selection="true" :row-no="true" :pagination="true"
			@update="updateBtn" @delete="deleteBtn" @current-change="currentChange" @selection-change="selectionChange">
		</vk-data-table>
		<!-- 表格组件结束 -->

		<!-- 添加或编辑的弹窗开始 -->
		<vk-data-dialog v-model="form1.props.show" :title="form1.props.title" width="700px" mode="form"
			:close-on-click-modal="false">
			<vk-data-form v-model="form1.data" :rules="form1.props.rules" :action="form1.props.action"
				:form-type="form1.props.formType" :columns='form1.props.columns' label-width="90px"
				@success="form1.props.show = false;refresh();"></vk-data-form>
		</vk-data-dialog>
		<!-- 添加或编辑的弹窗结束 -->

		<!-- 添加或编辑的弹窗开始 -->
		<vk-data-dialog v-model="form2.props.show" :title="form2.props.title" width="700px" mode="form"
			:close-on-click-modal="false">
			<vk-data-form v-model="form2.data" :rules="form2.props.rules" :action="form2.props.action"
				:form-type="form2.props.formType" :columns='form2.props.columns' label-width="120px"
				@success="form2.props.show = false;refresh();">
				<template v-slot:footer="{ loading }">
					<view style="text-align: center;">
						<el-button :loading="loading" type="danger" style="padding: 10px 40px;margin-right: 30px; "
							@click="form2.props.show=false"> 取消 </el-button>
						<el-button :loading="loading" type="success" style="padding: 10px 40px; "
							@click="batchAdd(form2.data)"> 确定
						</el-button>
					</view>
				</template>
			</vk-data-form>
		</vk-data-dialog>
		<!-- 添加或编辑的弹窗结束 -->

		<!-- 页面内容结束 -->
	</view>
</template>

<script>
	var that; // 当前页面对象
	var vk = uni.vk; // vk实例
	var originalForms = {}; // 表单初始化数据
	const db = uniCloud.database();
	export default {
		data() {
			// 页面数据变量
			return {
				// 页面是否请求中或加载中
				loading: false,
				// init请求返回的数据
				data: {

				},
				// 表格相关开始 -----------------------------------------------------------
				table1: {
					// 表格数据请求地址
					action: "admin/pages/kh/dsjzxgl/dsjfjgl/getList",
					// 表格字段显示规则
					columns: [
						// {"key":"_id","title":"ID，系统自动生成","type":"text","width":200},
						{
							key: "",
							title: "主剧信息",
							type: "group",
							minWidth: 200,
							align: "left",
							columns: [{
									key: "tv_name",
									title: "剧名",
									type: "text"
								},
								{
									key: "tv_id",
									title: "主剧ID",
									type: "text"
								},
								{
									key: "_id",
									title: "本集ID",
									type: "text"
								}
							],
						},
						{
							key: "",
							title: "分集信息",
							type: "group",
							minWidth: 160,
							align: "left",
							columns: [{
									key: "title",
									title: "标题",
									type: "text"
								},
								{
									key: "series",
									title: "第几集",
									type: "number"
								},
							],
						},

						{
							"key": "pay",
							"title": "付费金豆数",
							"type": "number",
							"width": 200
						},

						{
							key: "",
							title: "绑定小程序信息",
							type: "group",
							minWidth: 200,
							align: "left",
							columns: [{
									key: "appid",
									title: "appid",
									type: "text",
									defaultValue: "未绑定"
								},
								{
									key: "appname",
									title: "小程序名称",
									type: "text",
									defaultValue: "未绑定"
								},
							],
						},
						{
							"key": "_add_time_str",
							"title": "添加时间字符串",
							"type": "text",
							"width": 200
						}
					],
					// 多选框选中的值
					multipleSelection: [],
					// 当前高亮的记录
					selectItem: ""
				},
				// 表格相关结束 -----------------------------------------------------------
				// 表单相关开始 -----------------------------------------------------------
				// 查询表单请求数据
				queryForm1: {
					// 查询表单数据源，可在此设置默认值
					formData: {

					},
					// 查询表单的字段规则 fieldName:指定数据库字段名,不填默认等于key
					columns: [{
							"key": "tv_name",
							"title": "电视剧名",
							"type": "text",
							"width": 200,
							"mode": "%%"
						},

						{
							"key": "pay",
							"title": "付费金额",
							"type": "number",
							"width": 200,
							"mode": "="
						},
						{
							"key": "title",
							"title": "标题",
							"type": "text",
							"width": 200,
							"mode": "%%"
						}

					]
				},
				form1: {
					// 表单请求数据，此处可以设置默认值
					data: {
						pay: 0,

					},
					// 表单属性
					props: {
						// 表单请求地址
						action: "",
						// 表单字段显示规则
						columns: [{
								key: "tv_id",
								title: "选主剧",
								type: "table-select",
								placeholder: "选择",
								action: "admin/pages/kh/dsjzxgl/dsj/getList",
								columns: [{
										key: "tv_name",
										title: "剧名",
										type: "text",
										nameKey: true
									},

									{
										key: "_id",
										title: "剧id",
										type: "text",
										idKey: true
									},
									{
										key: "tv_image",
										title: "封面图",
										type: "image"
									},
								],
								watch: (res) => {
									// console.log("res=", res);
									// console.log("form1.data=", this._data.form1.data);
									this._data.form1.data = {
										tv_id: res.option._id,
										tv_name: res.option.tv_name,
										title: res.option.tv_name,
										tv_image: res.option.tv_image,
										desc: res.option.desc,
										pay: 0,
										like_num: 0,
										is_recommend: false,
										appname: []
									};
								}
							},
							{
								"key": "tv_id",
								"title": "ID标识",
								"type": "text",
								"disabled": true
							},
							{
								"key": "tv_name",
								"title": "主剧名称",
								"type": "text",
								"disabled": true
							},
							{
								"key": "series",
								"title": "第几集",
								"type": "number",
								watch: (res) => {
									console.log("watch", res)
									this._data.form1.data.title = this._data.form1.data.tv_name + " - 第" + res
										.value + "集"
								}
							},
							{
								"key": "tv_image",
								"title": "封面图",
								"type": "file-select",
								"placeholder": "请选择图片",
								"fileType": "image",
								"limit": 1
							},
							// {
							// 	"key": "video_src",
							// 	"title": "视频链接",
							// 	"type": "text"
							// },
							{
								"key": "title",
								"title": "标题",
								"type": "text"
							},
							{
								"key": "pay",
								"title": "付费金豆数",
								"type": "number",
								"tips": "用户需要付费的金豆数量，请填写正整数"
							},
							{
								"key": "",
								"title": "↓↓绑定了哪个小程序，该集就在哪个小程序的推荐列表中显示。不清楚可不选，不选则在全部小程序中展示↓↓",
								"type": "bar-title"
							},
							{
								key: "appname",
								title: "绑定小程序",
								tips: "不选则在所有小程序展示",
								type: "table-select",
								placeholder: "选择",
								action: "admin/pages/kh/xcxpz/xcxgl/getList",
								columns: [{
										key: "appid",
										title: "小程序appid",
										type: "text",
										nameKey: true
									},
									{
										key: "appname",
										title: "小程序名称",
										type: "text",
										idKey: true
									},
								],
								multiple: true,
								watch: (res) => {
									// console.log("watch", res.option)
									this.form1.data.appid = vk.pubfn.arrayObjectGetArray(res.option, "appid");
								}
							},

							{
								"key": "appname",
								"title": "小程序名称",
								"type": "text",
								"disabled": true,
								"tips": "不选则在所有小程序展示"
							},

						],
						// 表单验证规则
						rules: {
							pay: [{
									required: true,
									message: "金额不能为空，免费请填0",
									trigger: ['blur', 'change']
								},
								{
									type: "number",
									message: "必须是数字",
									trigger: ['blur', 'change']
								}
							],
							series: [{
									required: true,
									message: "请输入纯数字，1代表第一集",
									trigger: ['blur', 'change']
								},
								{
									type: "number",
									message: "必须是数字",
									trigger: ['blur', 'change']
								}
							],
							title: [{
								required: true,
								message: "请输入视频标题",
								trigger: ['blur', 'change']
							}],
							tv_image: [{
								required: true,
								message: "请填写封面图",
								trigger: ['blur', 'change']
							}],
						},
						// add 代表添加 update 代表修改
						formType: "",
						// 是否显示表单的弹窗
						show: false
					}
				},
				form2: {
					// 表单请求数据，此处可以设置默认值
					data: {
						pay: 99,
						appid: [],
						appname: []
					},
					// 表单属性
					props: {
						// 表单请求地址
						action: "",
						// 表单字段显示规则
						columns: [{
								key: "tv_id",
								title: "选主剧",
								type: "table-select",
								placeholder: "选择",
								action: "admin/pages/kh/dsjzxgl/dsj/getList",
								columns: [{
										key: "tv_name",
										title: "剧名",
										type: "text",
										nameKey: true
									},
									{
										key: "_id",
										title: "剧id",
										type: "text",
										idKey: true
									},
									{
										key: "tv_image",
										title: "封面图",
										type: "image"
									},
								],
								watch: (res) => {
									console.log("res=", res);
									this._data.form2.data = {};
									if (res.option.update_witch == res.option.all_series) {
										vk.alert('当前已更新集数等于总集数，无法添加更多集');
										return;
									}
									this._data.form2.data = {
										tv_id: res.formData.tv_id,
										tv_name: res.option.tv_name,
										update_witch: res.option.update_witch,
										all_series: res.option.all_series,

										title: res.option.tv_name,
										tv_image: res.option.tv_image,
										start_needpay: res.option.start_needpay,
										desc: res.option.desc,
										pay: 99,

										appid: [],
										appname: [],
									};

								}
							},
							{
								"key": "tv_id",
								"title": "ID标识",
								"type": "text",
								"disabled": true
							},
							{
								"key": "tv_name",
								"title": "主剧名称",
								"type": "text",
								"disabled": true
							},

							{
								"key": "update_witch",
								"title": "已更新剧集",
								"type": "number",
								"disabled": true
							},
							{
								"key": "all_series",
								"title": "总集数",
								"type": "number",
								"disabled": true
							},
							{
								"key": "series",
								"title": "更新至第几集",
								"type": "number",
								watch: (res) => {
									console.log("watch", res)
								},

							},
							{
								"key": "tv_image",
								"title": "封面图",
								"type": "image",
								"placeholder": "请选择图片",
								"fileType": "image",
								"limit": 1,
								"disabled": true
							},

							{
								"key": "pay",
								"title": "付费金豆数",
								"type": "number",
								"tips": "用户需要付费的金豆数量，请填写正整数"
							}
						],
						// 表单验证规则
						rules: {
							pay: [{
									required: true,
									message: "金额不能为空，免费请填0",
									trigger: ['blur', 'change']
								},
								{
									type: "number",
									message: "必须是数字",
									trigger: ['blur', 'change']
								}
							],
							series: [{
									required: true,
									message: "请输入纯数字，1代表第一集",
									trigger: ['blur', 'change']
								},
								{
									type: "number",
									message: "必须是数字",
									trigger: ['blur', 'change']
								}
							],

							title: [{
								required: true,
								message: "请输入视频标题",
								trigger: ['blur', 'change']
							}],
							tv_image: [{
								required: true,
								message: "请填写封面图",
								trigger: ['blur', 'change']
							}],
						},
						// add 代表添加 update 代表修改
						formType: "",
						// 是否显示表单的弹窗
						show: false
					}
				},

				// 其他弹窗表单
				formDatas: {},
				// 表单相关结束 -----------------------------------------------------------
			};
		},
		// 监听 - 页面每次【加载时】执行(如：前进)
		onLoad(options = {}) {
			that = this;
			vk = that.vk;
			that.options = options;
			that.init(options);
			console.log("data=", this._data);
		},
		created() {
			window.mydata = this._data
		},
		// 监听 - 页面【首次渲染完成时】执行。注意如果渲染速度快，会在页面进入动画完成前触发
		onReady() {},
		// 监听 - 页面每次【显示时】执行(如：前进和返回) (页面每次出现在屏幕上都触发，包括从下级页面点返回露出当前页面)
		onShow() {
			// if (vk.vuex.get('$user.userInfo.role[0]') != "admin") {
			// 	vk.navigateToLogin();
			// }
			console.log("onshow=", this._data.form1);
			console.log("this._data.form1.data.pay", this._data.form1.data.pay);
		},
		// 监听 - 页面每次【隐藏时】执行(如：返回)
		onHide() {},
		// 函数
		methods: {
			// 页面数据初始化函数
			init(options) {
				originalForms["form1"] = vk.pubfn.copyObject(that.form1);
			},
			// 页面跳转
			pageTo(path) {
				vk.navigateTo(path);
			},
			// 表单重置
			resetForm() {
				vk.pubfn.resetForm(originalForms, that);
			},
			// 搜索
			search() {
				that.$refs.table1.search();
			},
			// 刷新
			refresh() {
				that.$refs.table1.refresh();
			},
			// 获取当前选中的行的数据
			getCurrentRow() {
				return that.$refs.table1.getCurrentRow();
			},
			// 监听 - 行的选中高亮事件
			currentChange(val) {
				that.table1.selectItem = val;
			},
			// 当选择项发生变化时会触发该事件
			selectionChange(list) {
				that.table1.multipleSelection = list;
			},
			// 显示添加页面
			async addBtn() {
				that.resetForm();
				that.form1.props.action = 'admin/pages/kh/dsjzxgl/dsjfjgl/add';
				that.form1.props.formType = 'add';
				that.form1.props.title = '添加';
				that.form1.props.show = true;

			},
			//显示批量添加页面
			batchaddBtn() {
				that.resetForm();
				that.form2.props.action = 'admin/pages/kh/dsjzxgl/dsjfjgl/add';
				that.form2.props.formType = 'add';
				that.form2.props.title = '添加';
				that.form2.props.show = true;
			},
			// 显示修改页面
			updateBtn({
				item
			}) {
				that.form1.props.action = 'admin/pages/kh/dsjzxgl/dsjfjgl/update';
				that.form1.props.formType = 'update';
				that.form1.props.title = '编辑';
				that.form1.props.show = true;
				that.form1.data = item;
			},
			// 删除按钮
			deleteBtn({
				item,
				deleteFn
			}) {
				deleteFn({
					action: "admin/pages/kh/dsjzxgl/dsjfjgl/delete",
					data: {
						_id: item._id
					},
				});
			},
			async batchAdd(item) {
				if (item._id) {
					vk.callFunction({
						url: 'admin/pages/kh/dsjzxgl/dsj/update',
						title: '请求中...',
						data: {
							tvinfo: this.form2.data
						},
						success: (data) => {
							this.form2.props.show = false; //关闭编辑窗口
							this.refresh()
						}
					});
					return;
				} else {
					if (!this.form2.data.update_witch) {
						vk.alert('必须填写更新集数');
						return;
					}
					if (!this.form2.data.pay) {
						vk.alert('参数不完整，请检查必填项');
						return;
					}


					let timenow = new Date().getTime();
					let update_series = this.form2.data.series; //更新到多少集
					let start_series = Number(this.form2.data.update_witch + 1); //从多少集开始更新
					let all_series = this.form2.data.all_series; //总集数
					let is_end = false;
					if (update_series >= all_series) {
						update_series = all_series,
							is_end = true
					}
					for (var i = start_series; i <= update_series; i++) {
						uni.showToast({
							title: i + "/" + update_series + "，请勿关闭浏览器...",
							icon: 'loading'
						})

						let serie = i;
						let pay_bean = this.form2.data.pay; //初始值为前端传过来的how_much金豆
						//未到收费集数，则收费为0
						if (serie < this.form2.data.start_needpay) {
							pay_bean = 0
						}
						let add = await db.collection('a_tv_series').add({
							tv_id: this.form2.data.tv_id,
							tv_name: this.form2.data.tv_name,
							series: serie,
							tv_image: this.form2.data.tv_image,
							pay: pay_bean,
							title: this.form2.data.tv_name + " - 第" + serie + "集",
							appid: [],
							appname: [],
							_add_time: timenow,
							_add_time_str: vk.pubfn.timeFormat(new Date(), "yyyy-MM-dd hh:mm:ss") || "0"
						})
					}
					//添加集数的时候自动更新电视剧更新到哪集
					const updatetvs = await db.collection('a_tv').where({
						_id: this.form2.data.tv_id
					}).update({
						update_witch: update_series
					})
					//如果剧集已更完，
					const updatetv_end = await db.collection('a_tv').where({
						_id: this.form2.data.tv_id,

					}).update({
						is_end: is_end
					})
					this.form2.props.show = false; //关闭编辑窗口
					vk.alert('恭喜！添加完成');
					this.refresh();
					location.reload()
				}
			},
			// 监听 - 批量操作的按钮点击事件
			batchBtn(index) {
				switch (index) {
					case 1:
						vk.callFunction({
							url: 'admin/pages/kh/dsjzxgl/dsjfjgl/batchdel',
							title: '请求中...',
							data: {
								msgs: this.table1.multipleSelection
							},
							success: (data) => {
								console.log("执行完成");
								this.refresh()
							}
						});
						break;
					case 2:
						//先用弹窗接受新的付费金豆数
						this.$prompt('请输入新的金豆数', '批量修改付费金豆数', {
							confirmButtonText: '确定',
							cancelButtonText: '取消',
							inputPattern: /^[0-9]*$/,
							inputErrorMessage: '金豆数量只能为正整数'
						}).then(({
							value
						}) => {
							vk.callFunction({
								url: 'admin/pages/kh/dsjzxgl/dsjfjgl/batch_edit_price',
								title: '请求中...',
								data: {
									newprice: value,
									msgs: this.table1.multipleSelection
								},
								success: (data) => {
									vk.toast("批量修改已完成");
									this.refresh()
								}
							});
						})
						break;
					default:
						break;
				}
			},
			update_appid() {
				uni.showModal({
					title: "注意！！",
					confirmText: "确认重置",
					content: "本功能将会把所有剧集绑定的appid重置为空，将会影响小程序推荐视频数据。2023年1月15日之前的版本需执行一次本操作！如不清楚，请先咨询技术人员",
					success(res) {
						if (res.confirm) {
							vk.callFunction({
								url: 'admin/pages/kh/dsjzxgl/dsjfjgl/update_appid',
								title: '请求中...',
								data: {

								},
								success: (data) => {
									that.$refs.table1.refresh();
								}
							});
						} else {
							vk.toast('已取消');
						}
					}
				})

			},
		},
		// 监听属性
		watch: {
			form1() {
				console.log("change");
			}
		},
		// 过滤器
		filters: {

		},
		// 计算属性
		computed: {
			pay() {
				this._data.form1.data.pay = this._data.form1.data.like_num
				console.log("computed");
			}
		}
	};
</script>
<style lang="scss" scoped>
	.page-body {}
</style>